<script setup>
import {computed, onBeforeMount, onMounted, ref, watch} from "vue";
import {getPersonalMusicDetail, getUserLikeMusic} from "@/api/music/music.js";
import SongPlay from "@/components/SongPlay.vue";
import {useRoute} from "vue-router";
import axios from "axios";
import {ElMessage, ElMessageBox} from "element-plus";
import {copy, gotoUserInfo, sendWsRequest} from "@/api/toMusicInfo.js";
import {useStore} from "@/stores/store.js";
import {
  createTogetherRoom,
  generateInviteInfo,
  getMyIdentity,
  getOwnerInfo,
  getOwnerSheet,
  getVisitorInfo
} from "@/api/together/together.js";
import {loadMySheets} from "@/api/sheet/sheet.js";

const musicList = ref([
  {
    id: 0,
    name: "",
    music: "",
    musician: "",
    createTime: "",
    cover: "",
    album: "",
    duration: "",
    isLike: null,
    likeCount: null,
    commentCount: null
  }
])
let sheetList = ref([])

// 这个账号应该是房主的账号
const account = localStorage.getItem('account')
const roomId = useStore().togetherRoomInfo.togetherRoomId
const route = useRoute()

// 用户名
const username = localStorage.getItem('username')
const avatar = localStorage.getItem('avatar')


// 房间另一个人信息，然后调用接口去查根据roomId查redis todo


// 是不是主人
const isOwner = ref(false)


var websocket;
onMounted(async () => {


  // 检查全局变量有没有创建过房间，如果有就直接使用以前的
  await createTogetherRoom()
  // 获取喜欢列表(歌单)
  let res1 = await getOwnerSheet(useStore().togetherRoomInfo.togetherRoomId, useStore().togetherRoomInfo.togetherPlayMusicSheet)
  if (res1.data === 'again') {
    // 重新进行加载
    useStore().resetTheWorld()
    await createTogetherRoom()
    let resa = await getOwnerSheet(useStore().togetherRoomInfo.togetherRoomId, useStore().togetherRoomInfo.togetherPlayMusicSheet)
    musicList.value = resa.data

  } else {
    musicList.value = res1.data
  }

  startSong()

  // 自己是不是主人
  let res2 = await getMyIdentity(useStore().togetherRoomInfo.togetherRoomId, account);
  isOwner.value = res2.data


  websocket = new WebSocket(`ws://localhost:20000/music/ws/together/${account}/${useStore().togetherRoomInfo.togetherRoomId}`)

  // websocket实例

  websocket.onopen = function (event) {
    console.log('WebSocket连接已建立');
    // 可以在这里发送消息，例如：
    // 不是主人的话，需要把另一个用户也就是主人的信息放到全局变量otherUser里，直接在websocket里完成吧
    if (!isOwner.value && !useStore().otherUser.exist) {
      getOwnerInfo(useStore().togetherRoomInfo.togetherRoomId).then((res) => {
        useStore().otherUser = res.data
      })
    } else if(isOwner.value && !useStore().otherUser.exist) {
      getVisitorInfo(useStore().togetherRoomInfo.togetherRoomId).then((res) => {
        if (res.data.exist != null) {
          useStore().otherUser = res.data
        }
      })
    }

  }

  websocket.onmessage = function (event) {
    const message = JSON.parse(event.data)
    console.log(message)
    // 开始进行处理
    if (message.type === 0) {
      // 这个是加入房间的报文，可以有个提示之类的
      ElMessage.success('你的好友已加入房间！')
      // 然后对otherUser进行修改
      if (!useStore().otherUser.exist) {
        useStore().otherUser = message.data
      }

    }
    else if (message.type === 1) {
      ElMessage.success('我接收到了')
      useStore().togetherRoomInfo.togetherPlayMusicIndex = message.data.musicIndex
      useStore().togetherRoomInfo.togetherPlayMusicSheet = message.data.musicSheet
    }
    else if (message.type === 2) {
      // 播放报文
      useStore().togetherRoomInfo.togetherPlayStatus = true
    }
    else if (message.type === 3){
      // 暂停报文
      useStore().togetherRoomInfo.togetherPlayStatus = false
    }
    else if (message.type === 4){
      // 调整进度报文
      useStore().togetherRoomInfo.togetherMusicPosition = message.data.content
      downPosition.value = message.data.content
    }


    else if (message.type === 10) {
      // 收到她分手的通知，选择接受，烧掉回忆的相片，就当作一切化作云烟

      useStore().resetTheWorld()

      window.location.reload()

      ElMessage.info('她已经离开')

    }

    // ElMessage.info('收到消息对象:' + message)
    console.log('收到消息对象:', message)
  }

  websocket.onerror = function (event) {
    ElMessage.error('WebSocket出现错误:', event)
    // 可以在这里考虑重新连接的策略，比如延迟一段时间后重新尝试连接
  }
  websocket.onclose = function (event) {
    ElMessage.error('WebSocket关闭了')
  }

})

const downPosition = ref(0)

// 然后去查看这个房间内有没有别人进来


// 监听 togetherPlayMusic 的变化
watch(() => useStore().togetherRoomInfo.togetherPlayMusicIndex, (newValue, oldValue) => {
  if (newValue === oldValue) return
  const data = {
      musicIndex: useStore().togetherRoomInfo.togetherPlayMusicIndex,
      musicSheet: useStore().togetherRoomInfo.togetherPlayMusicSheet
  }
  const message = {
    type: 1,
    data: data
  }
  sendWsRequest(websocket, message)
})

// 监听 togetherPlayMusic 的变化
watch(() => useStore().togetherRoomInfo.togetherPlayMusicSheet, (newValue, oldValue) => {
  if (newValue === oldValue) return
  getOwnerSheet(useStore().togetherRoomInfo.togetherRoomId, useStore().togetherRoomInfo.togetherPlayMusicSheet).then((res) => {
    musicList.value = res.data
  })

  const data = {
      musicIndex: 0,
      musicSheet: useStore().togetherRoomInfo.togetherPlayMusicSheet
  }
  const message = {
    type: 1,
    data: data
  }
  sendWsRequest(websocket, message)

})


// 传个id参数即可 音乐详细页面获取音乐的详细信息
const musicPlayInfo = computed(() => {
  const index = useStore().togetherRoomInfo.togetherPlayMusicIndex;
  const list = musicList.value;

  if (list && list[index]) {
    return {
      index: index,
      title: list[index].name,
      musician: list[index].musician,
      musicId: list[index].id,
      cover: list[index].cover,
      url: list[index].music
    }
  } else {
    return {
      index: null,
      title: '',
      musician: '',
      musicId: null,
      cover: '',
      url: ''
    }
  }
})




function toMusicInfo(index) {
  useStore().togetherRoomInfo.togetherPlayMusicIndex = index
}

function popSheet(id) {
  // 更新一下列表数据 达到立马起效的效果
  const sheetUrl = "/music/sheet/show_can_add?account=" +  localStorage.getItem("account") + "&musicId=" + id
  axios.get(sheetUrl
  ).then((res)=>{
    if (res.data.flag) {
      sheetList.value = res.data.data
    } else {
      console.log(res.data.message)
    }
  })
}
function addToSheet(sheetId, musicId) {

  // 发一个post请求，添加歌曲进歌单
  const formData = {
    sheetId: sheetId,
    musicId: musicId
  }
  const url = "/music/sheet/add_music"
  axios.post(url,
      JSON.stringify(formData)
  ).then((res)=>{
    if (res.data.flag) {
      ElMessage.success("添加成功")
      const sheetUrl = "/music/sheet/show_can_add?account=" +  localStorage.getItem("account") + "&musicId=" + musicId
      axios.get(sheetUrl
      ).then((res)=>{
        if (res.data.flag) {
          sheetList.value = res.data.data
        } else {
          console.log(res.data.message)
        }
      })

    } else {
      ElMessage.error("添加失败：" + res.data.message)
      console.log(res.data.message)
    }
  })

}

const nextSong = (index) => {
  // 当是最后一首歌的时候就切到第一首
  if (musicList.value.length === index+1) {
    toMusicInfo(0)
  }
  else if (musicList.value.length === 0) {
    ElMessage.error('无喜欢歌曲，无法完成切换')
  }
  else {
    toMusicInfo(index + 1)
  }
}
const preSong = (index) => {

  // 当是第一首歌的时候就切到最后一首
  if (index === 0) {
    toMusicInfo(musicList.value.length - 1)
  }
  else if (musicList.value.length === 0) {
    ElMessage.error('无喜欢歌曲，无法完成切换')
  }
  else {
    toMusicInfo(index-1)
  }
}
function startSong () {

  // if (useStore().togetherPlayMusic == null) {
  //   // 播放器里没有歌曲播放记录，自动播放列表第一首歌曲
  //   ElMessage.info('播放器里没有歌曲播放记录，自动播放列表第一首歌曲')
  //   toMusicInfo(0)
  // }

  if (musicList.value.length === 0) {
    ElMessage.error('播放器列表内无歌曲，无法完成播放')
  }
  else if (useStore().togetherRoomInfo.togetherPlayMusicIndex == null) {
    // 播放器里没有歌曲播放记录，自动播放列表第一首歌曲
    ElMessage.info('播放器里没有歌曲播放记录，自动播放列表第一首歌曲')
    toMusicInfo(0)
  }
  else {
    toMusicInfo(useStore().togetherRoomInfo.togetherPlayMusicIndex)
    // getPersonalMusicDetail(useStore().togetherPlayMusic).then((res) => {
    //   console.log(res.data)
    //   musicPlayInfo.value = {
    //     index: 0,
    //     title: res.data.name,
    //     musician: res.data.musician,
    //     musicId: res.data.id,
    //     cover: res.data.cover,
    //     url: res.data.music
    //   }
    // })


  }

}

const inviteOrSeeInviteeInfo = async () => {
  if (useStore().otherUser.exist) {
    // 如果已经邀请成功了，执行查看信息逻辑
    const otherAccount = useStore().otherUser.account
    gotoUserInfo(otherAccount)
  } else {
    // 如果还没成功就进行邀请逻辑，生成链接
    const formData = {
      inviterAccount: account,
      roomId: useStore().togetherRoomInfo.togetherRoomId,
      musicId: musicList.value[useStore().togetherRoomInfo.togetherPlayMusicIndex].id
    }
    const res = await generateInviteInfo(formData)
    const copyContent = res.data
    copy(copyContent)
  }
};

const cssStyle = computed(() => ({
  backgroundImage: `url(${musicPlayInfo.value.cover})`
}));

const finishTogether = () => {
  ElMessageBox.confirm(
      '所有关于她的一切都将成为泡影，你或许再也遇不到似她般的女孩，你还要继续吗',
      '三思',
      {
        confirmButtonText: '我决定好了',
        cancelButtonText: '我不能..',
        type: 'warning',
      }
  )
      .then(() => {
        // 直接删除他曾经来过的痕迹，就当她从未来过
        useStore().resetTheWorld()

        // 发一个退出报文，让他也关闭房间
        const message = {
          type: 10,
          data: null
        }
        sendWsRequest(websocket, message)

        // 刷新页面
        window.location.reload()
        ElMessage({
          type: 'success',
          message: '再也没了她，你也重获自由',
        })
        return
      })
      .catch(() => {
      })


  ElMessage({
    type: 'info',
    message: '一切都还是一切，平淡但有你',
  })

}

const sheets = ref([])
const loadSheets = () => {
  loadMySheets(localStorage.getItem('account')).then((res) => {
    sheets.value = res.data
  })
}
// 切换歌单
const switchSheet = (roomId, sheetId) => {
  getOwnerSheet(roomId, sheetId).then((res) => {
    musicList.value = res.data
    useStore().togetherRoomInfo.togetherPlayMusicSheet = sheetId
  })
}


</script>

<template>
  <div class="container">
    <div class="masker"></div>
    <div :style="cssStyle" class="player"></div>
    <el-scrollbar style="height: 70vh;
    margin: 0 8%;box-sizing: border-box;
    position: relative;top: 15vh;color: hsla(0, 0%, 88.2%, .8);
    z-index: 3;width: 1200px;">
      <div class="song-row grayBg">
        <span class="c1">歌曲</span>
        <span class="c2">歌手</span>
        <span class="c3">专辑</span>
        <span class="c4">时长</span>
      </div>
      <div class="song-row" style="position: relative;font-size: 15px" v-for="(item,index) in musicList" :key="index" :class="{grayBg :　index % 2 === 1}">
        <span class="index">{{ index + 1 }}</span>
        <div class="plugin" style="display: none;position: absolute;left: 400px;height: 50px;top: -11px">
          <i @click="toMusicInfo(index)" class="play-icon"></i>
          <el-popover placement="right" trigger="click">
            <template #reference>
              <i @click="popSheet(item.id)" class="add-icon"></i>
            </template>
            <el-table :data="sheetList">
              <el-table-column  label="歌单" >
                <template #default="scope">
                  <!-- 不仅查询所有歌单 还要查询歌曲对每个歌单的归属情况 -->
                  <div v-if="scope.row.canAdd" :class="{gery:　scope.row.canAdd}" style="width: 170px">{{ scope.row.name  }}</div>
                  <div v-else style="cursor:pointer;width: 170px" @click="addToSheet(scope.row.id,item.id)">{{ scope.row.name  }}</div>
                </template>
              </el-table-column>
            </el-table>
          </el-popover>
        </div>

        <span class="c1">
          <span class="hover" @click="toMusicInfo(index)" style="color: white;cursor:pointer;">{{ item.name }}</span>
        </span>

        <span class="c2">{{ item.musician }}</span>
        <span class="c3">{{ item.album }}</span>
        <span class="c4">{{ item.duration }}</span>
      </div>

    </el-scrollbar>

    <div style="position: relative;z-index: 3;top: 12vh">
      <div style="border-radius: 15px;background: rgba(255,255,255,0.05);position: relative;padding: 20px 20px 0;">
        <div style="width: 250px;height: 250px;box-shadow: inset 0 -70px 40px -15px rgba(72,72,72,0.5);border-radius: 10px">
          <img width="250" height="250" style="position: relative;z-index: -1;border-radius: 10px" :src="musicPlayInfo.cover">
          <p style="color:rgba(255,255,255,0.8);position: absolute;left: calc(145px - 3.5em);top: 240px;font-size: 14px">
            {{ useStore().otherUser.exist ? '我们正在一起听歌' : '等待好友加入中' }}
          </p>
        </div>

        <div style="display: flex;color: rgba(255,255,255,0.5);justify-content: center;gap: 10px;height: 70px;align-items: center">
          <span style="position: relative;left: 25px;">{{ username }}</span>
          <img style="position: relative;left: 25px;border-radius: 50%" width="40" height="40" :src="avatar">
          <svg style="scale: 0.25" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 1024 1024"><path fill="currentColor" d="M118.656 438.656a32 32 0 0 1 0-45.248L416 96l4.48-3.776A32 32 0 0 1 461.248 96l3.712 4.48a32.064 32.064 0 0 1-3.712 40.832L218.56 384H928a32 32 0 1 1 0 64H141.248a32 32 0 0 1-22.592-9.344zM64 608a32 32 0 0 1 32-32h786.752a32 32 0 0 1 22.656 54.592L608 928l-4.48 3.776a32.064 32.064 0 0 1-40.832-49.024L805.632 640H96a32 32 0 0 1-32-32"></path></svg>

          <el-tooltip :content="useStore().otherUser.exist ? '查看信息' : '点击复制邀请链接'" placement="top">
            <div @click="inviteOrSeeInviteeInfo" v-loading="!useStore().otherUser.exist"  element-loading-svg-view-box="-15, -15, 80, 80"
                 element-loading-background="rgba(0,0,0,0.5)" style="cursor:pointer;position: relative;right: 25px;border-radius: 50%;background: rgba(255,255,255,0);overflow: hidden;min-width: 40px;height: 40px;">
              <img style="border-radius: 50%" width="40" height="40" :src=" useStore().otherUser.avatar">
            </div>
          </el-tooltip>
          <span style="position: relative;right: 25px;">{{ useStore().otherUser.username }}</span>
        </div>

      </div>
    </div>

    <div class="operation-bar">

      <div style="right: 180px">
        <el-popover @before-enter="loadSheets()" trigger="click"
                    placement="bottom-start" style="right: 280px">
          <template #reference>
            <div style="display: flex;align-items: center;letter-spacing: 1px;gap: 5px">
              <svg width="17" height="17" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
                <path d="M42 19H5.99998" stroke="#ffffffb2" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/>
                <path d="M30 7L42 19" stroke="#ffffffb2" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/><path d="M6.79897 29H42.799" stroke="#f5f5f5" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/><path d="M6.79895 29L18.799 41" stroke="#f5f5f5" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/>
              </svg>
              <span>切换歌单</span>
            </div>
          </template>

          <el-table @header-click="switchSheet(useStore().togetherRoomInfo.togetherRoomId, null)" :data="sheets">

            <el-table-column label="默认">
              <template #default="scope">
                <span style="cursor: pointer!important;" @click="switchSheet(useStore().togetherRoomInfo.togetherRoomId, scope.row.id)">{{ scope.row.name }}</span>
              </template>
            </el-table-column>
          </el-table>


        </el-popover>
      </div>


      <div v-show="useStore().otherUser.exist" @click="finishTogether" style="right: 40px">
        <svg width="17" height="17" viewBox="0 0 48 48" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path d="M14.5 8C13.8406 8.37652 13.2062 8.79103 12.6 9.24051C11.5625 10.0097 10.6074 10.8814 9.75 11.8402C6.79377 15.1463 5 19.4891 5 24.2455C5 34.6033 13.5066 43 24 43C34.4934 43 43 34.6033 43 24.2455C43 19.4891 41.2062 15.1463 38.25 11.8402C37.3926 10.8814 36.4375 10.0097 35.4 9.24051C34.7938 8.79103 34.1594 8.37652 33.5 8"
                stroke="#ffffffb2" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/>
          <path d="M24 4V24" stroke="#ffffffb2" stroke-width="4" stroke-linecap="butt" stroke-linejoin="round"/></svg>
        <span>结束一起听</span>
      </div>
    </div>

    <SongPlay @next-song="nextSong" @pre-song="preSong"
              :isOwner="isOwner"
              :song="musicPlayInfo" :websocket="websocket" :downPosition="downPosition"
        style="z-index: 9999;padding-bottom: 50px;background: rgba(255,255,255,0);box-shadow: none"
       ></SongPlay>


  </div>
</template>
<style scoped>
.container {
  position: relative;
  height: 100vh;
  width: 100vw;
  overflow: hidden;
  background-color: rgb(23, 47, 101);
  display: flex;
}
.operation-bar {

}
.operation-bar > * {
  position: absolute;
  top: 15px;
  z-index: 99;
  font-size: 14px;
  cursor: pointer;
  border-radius: 18px;
  display: flex;
  align-items: center;
  gap: 5px;
  padding: 6px 14px;
  color: rgba(255,255,255,0.7);
  background: rgba(255,255,255,0.1);
  letter-spacing: 1px;
}
.masker {
  background-color: rgba(0, 0, 0, .35);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden;
  z-index: 2;
}
.player {
  background-repeat: no-repeat;
  background-size: cover;
  background-position: 50%;
  filter: blur(65px);
  opacity: .6;
  transform: translateZ(0);
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  overflow: hidden
}
.song-row:hover > .plugin {
  display: block!important;

}
.gery {
  color: #ababab !important;
  cursor: default!important;
}
i {
  width: 72px;
  height: 72px;
  margin-right: -4px;
  margin-left: -6px;
  display: inline-block;
  background: url("/src/assets/img/total3.png") no-repeat;
  cursor: pointer;
}

.play-icon {
  background-position: 0 0;
  transform: scale(0.5);
  margin-bottom: 2px;
}
.play-icon:hover {
  background-position: -80px 0;
}
.add-icon {
  background-position: -0px -160px;
  transform: scale(0.5);
  margin-bottom: 2px;
}
.add-icon:hover {
  background-position: -80px -160px;

}

.index {
  position: absolute;
  top: 0;
  left: 10px;
  width: 36px;
}
.items {
  color: white;
  height: 57px;
}
.items>span {
  line-height: 57px;
  margin-right: 40px;
  cursor: pointer;
}
.items>span:hover {
  color: #e96161;
}
.active {
  color: #e96161;
}
.grayBg {
  background: rgba(0,0,0,.01);
}
.song-row {
  line-height: 50px;
  font-size: 14px;
  padding-left: 46px;
  position: relative;
  display: flex;
  width: 1200px;
  box-sizing: border-box;
  font-family: poppin,Tahoma,Arial,\5FAE\8F6F\96C5\9ED1,sans-serif;
}
.hover:hover {
  color: #e96161;
}

.song-row>span {
  display: inline-block;
}
.c1 {
  width: 504px;
}
.c2 {
  width: 255px;
  padding-left: 15px;
}
.c3 {
  width: 255px;
  padding-left: 15px;
}
.c4 {
  position: absolute;
  top: 0;
  right: 38px;
  width: 50px;
}
* {
  font-family: poppin,Tahoma,Arial,\5FAE\8F6F\96C5\9ED1,sans-serif;
}
</style>
